package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    //根据u/p查询数据库
    @Override
    public String findUserByUP(User user) {
        //1.将密码加密
        byte[] bytes = user.getPassword().getBytes();
        String md5Pass = DigestUtils.md5DigestAsHex(bytes);
        user.setPassword(md5Pass);
        //2.根据用户名和密文查询数据库
        User userDB = userMapper.findUserByUP(user);
        //3.判断userDB是否有值
        if(userDB == null){
            //查询没有数据.返回null
            return null;
        }
        return UUID.randomUUID().toString().replace("-", "");
    }

    @Override
    public PageResult getUserListByPage(PageResult pageResult) {
        long total = userMapper.findTotal(pageResult);
        int size = pageResult.getPageSize();
        int start = (pageResult.getPageNum()-1)*size;
        String query = pageResult.getQuery();
        List<User> list = userMapper.getUserListByPage(size,start,query);
        return pageResult.setTotal(total).setRows(list);
    }

    @Override
    public int changById(User user) {
        int row = userMapper.changById(user);
        return row;
    }

    @Override
    public int addUser(User user) {
        String password = user.getPassword();
        String MD5Pass = DigestUtils.md5DigestAsHex(password.getBytes());
        Date date = new Date();
        user.setPassword(MD5Pass).setStatus(true).setCreated(date).setUpdated(date);
        int i = userMapper.addUser(user);
        return i;
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override
    public void updateUser(User user) {
        Date date = new Date();
        user.setUpdated(date);
        userMapper.updateUser(user);
    }
    /**
     * @Transactional
     * 1.默认只拦截运行时异常
     * 2.roolbackFor：指定异常类型回滚 rollbackFor=RuntimeExecption.class
     * 3.NoroolbackFor：指定异常不会滚
     * */
    @Transactional
    @Override
    public void deleteUserById(Integer id) {
        userMapper.deleteUserById(id);
//        int a=10/0;测试异常
    }

}
